<template>
  <div class="goods-image">
    <div
      class="large"
      v-show="show"
      :style="[
        { backgroundImage: `url(${images[currIndex]})` },
        largetPosition
      ]"
    />
    <div class="middle" ref="target">
      <img :src="images[currIndex]" alt="" />
      <div class="layer" v-show="show" :style="layerPosition" />
    </div>
    <ul class="small">
      <li
        v-for="(img, i) in images"
        :key="img"
        :class="{ active: i === currIndex }"
      >
        <img @mouseenter="currIndex = i" :src="img" alt="" />
      </li>
    </ul>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import { useMouseInElement } from "@vueuse/core";
interface Props {
  images: string[];
}
defineProps<Props>();
const currIndex = ref(0);
const target = ref(null);
// 是否显示遮罩和大图
const show = ref(false);
// 遮罩层的坐标
const layerPosition = reactive({
  left: "0px",
  top: "0px"
});
// 大图的定位
const largetPosition = reactive({
  backgroundPositionX: "0px",
  backgroundPositionY: "0px"
});
const { elementX, elementY, isOutside } = useMouseInElement(target);
watch([elementX, elementY, isOutside], () => {
  const position = {
    x: 0,
    y: 0
  };
  if (elementX.value < 100) {
    position.x = 0;
  } else if (elementX.value > 300) {
    position.x = 200;
  } else {
    position.x = elementX.value - 100;
  }
  if (elementY.value < 100) {
    position.y = 0;
  } else if (elementY.value > 300) {
    position.y = 200;
  } else {
    position.y = elementY.value - 100;
  }
  layerPosition.left = position.x + "px";
  layerPosition.top = position.y + "px";
  largetPosition.backgroundPositionX = -position.x * 2 + "px";
  largetPosition.backgroundPositionY = -position.y * 2 + "px";
  isOutside.value ? (show.value = false) : (show.value = true);
});
</script>
<style scoped lang="scss">
.goods-image {
  position: relative;
  z-index: 500;
  display: flex;
  width: 480px;
  height: 400px;

  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    background-color: #f8f8f8;
    background-repeat: no-repeat;
    background-size: 800px 800px;
    box-shadow: 0 0 10px rgb(0 0 0 / 10%);
  }

  .middle {
    position: relative;
    width: 400px;
    height: 400px;
    cursor: move;
    background: #f5f5f5;

    img {
      width: 100%;
      height: 100%;
    }

    .layer {
      position: absolute;
      top: 0;
      left: 0;
      width: 200px;
      height: 200px;
      background: rgb(0 0 0 / 20%);
    }
  }

  .small {
    width: 80px;

    li {
      width: 68px;
      height: 68px;
      margin-bottom: 15px;
      margin-left: 12px;
      cursor: pointer;

      &:hover,
      &.active {
        border: 2px solid $xtxColor;
      }

      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
